package com.atguigu.juc1205.demo;

/**
 * @Author Joey
 * @Date 2021/9/24 15:00
 * @Description 两个线程。可以操作初始值为 0 的变量，
 * 实现一个线程 +1 ，一个线程 -1，
 * 实现交替，变量初始值为 0
 * 1、高内聚低耦合前提 线程操作资源类
 * 2、判断、干活、通知
 * 3、防止虚假唤醒 使用 while 进行判断
 */
public class ProdConsumerDemo04 {

    public static void main(String[] args) throws Exception {

        AirCondition airCondition = new AirCondition();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    airCondition.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "线程A").start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    airCondition.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "线程B").start();

    }

}

class AirCondition {
    private int num = 0;

    public synchronized void increment() throws InterruptedException {
        //判断
//        if (num != 0) {
        while (num != 0) {
            this.wait();
        }
        //干活
        num++;
        System.out.println(Thread.currentThread().getName() + "  " + num);
        //通知
        this.notifyAll();
    }

    public synchronized void decrement() throws InterruptedException {
        //判断
//        if (num == 0) {
        while (num == 0) {
            this.wait();
        }
        //干活
        num--;
        System.out.println(Thread.currentThread().getName() + "  " + num);
        //通知
        this.notifyAll();
    }

}
